﻿package net.wangit.jdbc.connection;

import net.wangit.framework.exception.ConfigurationException;
import net.wangit.jdbc.JDBCException;
import net.wangit.util.Checker;
import net.wangit.util.XMLUtil;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dom4j.Element;


public final class ConnectionProviderFactory {

	private static final Log log = LogFactory
			.getLog(net.wangit.jdbc.connection.ConnectionProviderFactory.class);

	public static ConnectionProvider getConnectionProvider(String path,
			Element root) throws ConnectionException, JDBCException {
		ConnectionProvider connectionProvider;
		Element connectionNode = root.element("proxool");
		if (connectionNode != null) {
			connectionProvider = new ProxoolConnectionProvider();
			connectionProvider.configure(path, connectionNode);
			return connectionProvider;
		}

		connectionNode = root.element("datasource");
		String jndiName = null;
		if (connectionNode != null)
			jndiName = XMLUtil.getTextString(connectionNode, "jndi-name", null);
		if (!Checker.isEmpty(jndiName)) {
			connectionProvider = new DatasourceConnectionProvider();
		} else {
			connectionNode = root.element("driver");
			if (connectionNode == null) {
				log.error("could not found <driver> element in datasource file!");
				throw new ConfigurationException(path, "driver");
			}
			connectionProvider = new DriverManagerConnectionProvider();
		}
		connectionProvider.configure(path, connectionNode);
		return connectionProvider;
	}

	private ConnectionProviderFactory() {
	}

}
